import { ADDTOCAR, COMOPUTE, SUBTOCAR, SWITCHSELECT, REMOVEITEMCAR, REMOVEBYCHECK, SWITCHALLCHECK } from "./cartActions";

const initState = {
  /**
   * {
   *    id: string,
   *    image: string,
   *    title: string,
   *    price: number,
   *    count: number,
   *    check: boolean,
   * }
   *
   * */
  // 购物车
  list: [],
  // 总选中价钱
  selectAllPrice: 0,
  // 总数量
  allCount: 0,
  // 全选状态
  allCheck: false
};

export const cartReducer = (prevState = initState, action) => {
  switch (action.type) {
    // 数量 +
    case ADDTOCAR: {
      const payload = action.payload;
      const item = prevState.list.find((v) => v.id === payload.id);

      if (item) item.count++;
      else {
        prevState.list.push(payload);
      }

      return {
        ...prevState,
        list: [...prevState.list],
      };
    }
    // 数量 -
    case SUBTOCAR: {
      const payload = action.payload;
      const item = prevState.list.find((v) => v.id === payload.id);

      if (item) item.count--;
      return {
        ...prevState,
        list: [...prevState.list],
      };
    }
    // 计算
    case COMOPUTE: {
      const { list } = prevState;
      return {
        ...prevState,
        selectAllPrice: list.reduce((p, n) => {
          return n.check ? p + n.count * n.price : p;
        }, 0),
        allCount: list.reduce((p, n) => {
          return p + n.count;
        }, 0),
        allCheck: list.every((v) => v.check)
      };
    }
    //  单选切换
    case SWITCHSELECT: {
      const {payload} = action;

      const item = prevState.list.find(v => {
        console.log('id-----',v.id, payload.id, '---------id')
        return v.id === payload.id
      });
      if(item) item.check = !item.check;
      
      return {
        ...prevState,
        list: [...prevState.list]
      }
    }
    // 单项删除
    case REMOVEITEMCAR: {
      const id = action.payload;
      const newList = prevState.list.filter(v => v.id !== id);

      return {
        ...prevState,
        list: newList
      }
    }
    // 删除所选
    case REMOVEBYCHECK: {
      return {
        ...prevState,
        list: prevState.list.filter(v => v.check === false)
      }
    }
    case SWITCHALLCHECK: {
      return {
        ...prevState,
        list: prevState.list.map(v => {
          v.check = action.payload
          return v
        })
      }
    }
    default:
      return prevState;
  }
};
